﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RFinance.Domain.Concrete;
using RFinance.Domain.Entities;
using RFinance.Infrastructure.Abstract;


namespace RFinance.Controllers
{
    public class AccountController : Controller
    {

        private GenericRepository<RFinanceContext, User> repository;
        private IAuthProvider authentication;

        public AccountController(GenericRepository<RFinanceContext, User> repo, IAuthProvider auth)
        {
            repository = repo;
            authentication = auth;
        }

        public ViewResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(User user)
        {
            if (ModelState.IsValid && authentication.Authenticate(user.Email, user.Password))
            {
                ViewBag.NomeUsuario = user.Username;
                return new RedirectResult("/Home");
            }
            else
            {
                return View();
            }
        }

        public ActionResult Create()
        {            
            return View();
        }

        [HttpPost]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    repository.Add(user);
                    repository.Save();
                    ViewBag.NomeUsuario = user.Username;
                    if (authentication.Authenticate(user.Email, user.Password))
                    {
                        return new RedirectResult("/Home");
                    }
                    else
                    {
                        return View();
                    }

                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Usuário existente");
                    return View();
                }
            }
            else
            {
                return View();
            }
        }
    }
}
